package Sever;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Vector;

import libarary.Contants;
import libarary.Contants.state;

public class ServerUdp implements Contants{
	
	DatagramSocket serverSocket;
	DatagramPacket receivePacket;
	DatagramPacket sendPacket;
	InetAddress IPAddress;
	byte[] receiveData = new byte[1024];
	int portcl;
	User us;
	Vector uslist;
	public ServerUdp() {
		try {
			serverSocket = new DatagramSocket(9876);
		} catch (SocketException ex) {
			ex.printStackTrace();
		}
	}

	public void senDadta(String st) {
		try {
			sendPacket = new DatagramPacket(st.getBytes(),st.getBytes().length, IPAddress, portcl);
			serverSocket.send(sendPacket);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public String receiveData() {

		try {
			DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
			serverSocket.receive(receivePacket);
			IPAddress = receivePacket.getAddress();
			portcl = receivePacket.getPort();
			return new String(receivePacket.getData()).trim();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
	public String ChekLogin(String st){
		us=new User();
		st=st.substring(1);
		String name=st.substring(0, st.indexOf(state.noichuoi));
		
		String ps=st.substring(st.indexOf(state.noichuoi)+state.noichuoi.length(),st.length() );
		System.out.print(ps);
		if(us.Login(name,ps )!=null){
			return name;
		}
		return state.error;
	}
	public int checkReceiveData(String st){
		char tv=st.charAt(0);
		if(tv=='0')
			return 0;
		return 1;
	}
	public String Task(String st){
		int tv=checkReceiveData(st);
		switch(tv){
		case 0:
			return ChekLogin(st);
		}
		return "";
	}
	public static void main(String args[]) {

		ServerUdp sv = new ServerUdp();
		while (true) {
			String kq = sv.receiveData();
			
			sv.senDadta(sv.Task(kq));
			//System.out.print("server");
		}
	}
	
}
